<?php

namespace App\Admin\Forms;

use App\Models\CustomColumn;
use App\Models\DeviceCategory;
use App\Models\DeviceRecord;
use App\Models\DeviceTrack;
use App\Models\ImportLog;
use App\Models\ImportLogDetail;
use App\Models\User;
use App\Models\VendorRecord;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Exception\UnsupportedTypeException;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Widgets\Form;
use Dcat\EasyExcel\Excel;
use Exception;
use Illuminate\Contracts\Filesystem\FileNotFoundException;

class UserListImportForm extends Form
{
    /**
     * 处理表单提交逻辑.
     *
     * @param array $input
     *
     * @return JsonResponse
     */
    public function handle(array $input): JsonResponse
    {
        $file = $input['file'];
        $file_path = storage_path('app/public/' . $file);

        $success = 0;
        $fail = 0;
        $admin = Admin::user();
        $import_log = new ImportLog();
        $import_log->item = get_class(new User());
        $import_log->operator = $admin->id;
        $import_log->save();

        try {
            $rows = Excel::import($file_path)->first()->toArray();

            foreach ($rows as $row) {
                $asset_number = $row['姓名'] . '-' . $row['身份证号'] ?? '未知';
                try {
                    if (!empty($row['姓名']) && !empty($row['身份证号']) && !empty($row['手机号码']) && !empty($row['银行卡号'])) {
                        $userModel = new User();
                        $userModel->company_id = $admin->company_id;
                        $userModel->realname = $row['姓名'];
                        $userModel->phone = $row['手机号码'];
                        $userModel->id_number = $row['身份证号'];

                        // 这里导入判断空值，不能使用 ?? null 或者 ?? '' 的方式，写入数据库的时候
                        // 会默认为插入''而不是null，这会导致像price这样的double也是插入''，就会报错
                        // 其实price应该插入null
                        $exist = User::where('id_number', $row['身份证号'])->where(['company_id' => $admin->company_id, 'agent' => $admin->id])->withTrashed()->first();
                        if (!empty($exist)) {
                            $fail++;
                            ImportLogDetail::query()->create([
                                'log_id' => $import_log->id,
                                'log' => $asset_number . '：导入失败，医生信息已经存在！'
                            ]);
                            continue;
                        }
                        $userModel->unit = $row['医院名称（单位）'];
                        $userModel->unit_level = $this->getUnitLevel($row['医院级别']);
                        $userModel->department = $row['科室'];
                        $userModel->title = $this->getUserTitle($row['职称']);
                        $userModel->bank_number = $row['银行卡号'];
                        $userModel->bank_opening = $row['开户行（银行全称）'];
                        $userModel->bank_account_open_local = $row['开户地（省市区）'];
                        $userModel->agent = $admin->id;
                        $userModel->agent_code = $admin->employee_number;
                        $userModel->status = 1;
                        $userModel->ip = request()->ip();
                        $userModel->save();

                        $success++;
                        // 导入日志写入
                        ImportLogDetail::query()->create([
                            'log_id' => $import_log->id,
                            'status' => 1,
                            'log' => $asset_number . '：导入成功！'
                        ]);
                    } else {
                        $fail++;
                        // 导入日志写入
                        ImportLogDetail::query()->create([
                            'log_id' => $import_log->id,
                            'log' => $asset_number . '：导入失败，缺少必要的字段：姓名、身份证号、银行卡号！'
                        ]);
                    }
                } catch (Exception $exception) {
                    $fail++;
                    // 导入日志写入
                    ImportLogDetail::query()->create([
                        'log_id' => $import_log->id,
                        'log' => $asset_number . '：导入失败，' . $exception->getMessage()
                    ]);
                }
            }
            @unlink($file_path);
            $return = $this->response()
                ->success('导入成功：' . ': ' . $success . ' ; ' . '导入失败：' . ': ' . $fail)
                ->refresh();
        } catch (IOException $exception) {
            $return = $this
                ->response()
                ->error('写入数据库失败' . $exception->getMessage());
        } catch (UnsupportedTypeException $exception) {
            $return = $this->response()
                ->error('文件格式有误' . $exception->getMessage());
        } catch (FileNotFoundException $exception) {
            $return = $this->response()
                ->error('没有找到文件' . $exception->getMessage());
        }

        return $return;
    }

    /**
     * 构造表单.
     */
    public function form()
    {
        $this->file('file', '文件')
            ->accept('xlsx,csv')
            ->disk('public')
            ->autoUpload()
            ->uniqueName()
            ->required()
            ->help('仅支持xlsx,csv格式文件 , <a href="https://tofund.high-med.cn/user-excel/医生信息表.xlsx" target="_blank"><span style="color:red;">下载医生信息模板</span></a>');
    }

    protected function getUnitLevel($str)
    {
        $level = ['一级' => '1', '二级' => '2', '三级' => '3'];
        return isset($level[$str]) ? $level[$str] : '';
    }

    protected function getUserTitle($str)
    {
        $title = ['住院医师' => 1, '主治医师' => 2, '副主任医师' => 3, '主任医师' => 4];
        return isset($title[$str]) ? $title[$str] : '';
    }
}
